#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import json
import re
import random
import requests
from datetime import datetime, timedelta
from collections import Counter
import logging
from logging.handlers import RotatingFileHandler

# 添加当前目录到Python路径
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, current_dir)

try:
    from flask import Flask, request, jsonify, Blueprint
    from flask_sqlalchemy import SQLAlchemy
    from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity
    from flask_cors import CORS
    from werkzeug.security import generate_password_hash, check_password_hash
    from sqlalchemy import func
    import pymysql
    from bs4 import BeautifulSoup
except ImportError as e:
    print(f"缺少依赖包: {e}")
    print("请运行: pip install flask flask-sqlalchemy flask-jwt-extended flask-cors pymysql beautifulsoup4")
    sys.exit(1)

# 导入重构后的模块
from services.crawler_service import CrawlerService
from services.lottery_crawler import LotteryCrawler
from services.analysis_service import AnalysisService
from services.ai_service import AIService
from utils.validators import DataValidator
from utils.data_formatter import DataFormatter

def create_app():
    """创建Flask应用"""
    app = Flask(__name__)
    
    # 配置
    app.config['SECRET_KEY'] = 'your-secret-key-here'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:mario@localhost/ai_ssq?charset=utf8mb4'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['JWT_SECRET_KEY'] = 'jwt-secret-string'
    app.config['JWT_TOKEN_LOCATION'] = ['headers']
    app.config['JWT_HEADER_NAME'] = 'Authorization'
    app.config['JWT_HEADER_TYPE'] = 'Bearer'
    
    # 初始化扩展
    db = SQLAlchemy(app)
    jwt = JWTManager(app)
    CORS(app)
    
    # 配置日志
    if not os.path.exists('logs'):
        os.mkdir('logs')
    file_handler = RotatingFileHandler('logs/ai_ssq.log', maxBytes=10240, backupCount=10)
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
    ))
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
    app.logger.setLevel(logging.INFO)
    app.logger.info('AI双色球分析助手启动')
    
    # 初始化服务
    crawler_service = CrawlerService()
    analysis_service = AnalysisService()
    ai_service = AIService()
    
    # 注册蓝图
    register_blueprints(app, db, crawler_service, analysis_service, ai_service)
    
    return app, db

def register_blueprints(app, db, crawler_service, analysis_service, ai_service):
    """注册蓝图"""
    
    # 数据库模型定义
    class LotteryResult(db.Model):
        __tablename__ = 'lottery_results'
        id = db.Column(db.Integer, primary_key=True)
        draw_date = db.Column(db.Date, nullable=False)
        draw_number = db.Column(db.String(20), unique=True, nullable=False)
        red_ball_1 = db.Column(db.Integer, nullable=False)
        red_ball_2 = db.Column(db.Integer, nullable=False)
        red_ball_3 = db.Column(db.Integer, nullable=False)
        red_ball_4 = db.Column(db.Integer, nullable=False)
        red_ball_5 = db.Column(db.Integer, nullable=False)
        red_ball_6 = db.Column(db.Integer, nullable=False)
        blue_ball = db.Column(db.Integer, nullable=False)
        prize_info = db.Column(db.Text)
        created_at = db.Column(db.DateTime, default=db.func.current_timestamp())
        
        def get_red_balls(self):
            return [self.red_ball_1, self.red_ball_2, self.red_ball_3, 
                    self.red_ball_4, self.red_ball_5, self.red_ball_6]
        
        def to_dict(self):
            return {
                'id': self.id,
                'draw_date': self.draw_date.isoformat() if self.draw_date else None,
                'draw_number': self.draw_number,
                'red_ball_1': self.red_ball_1,
                'red_ball_2': self.red_ball_2,
                'red_ball_3': self.red_ball_3,
                'red_ball_4': self.red_ball_4,
                'red_ball_5': self.red_ball_5,
                'red_ball_6': self.red_ball_6,
                'blue_ball': self.blue_ball,
                'prize_info': self.prize_info,
                'created_at': self.created_at.isoformat()
            }
    
    class AIPrediction(db.Model):
        __tablename__ = 'ai_predictions'
        id = db.Column(db.Integer, primary_key=True)
        start_draw = db.Column(db.String(20), nullable=False)
        end_draw = db.Column(db.String(20), nullable=False)
        data_count = db.Column(db.Integer, nullable=False)
        predicted_numbers = db.Column(db.Text, nullable=False)
        actual_result = db.Column(db.Text)
        win_info = db.Column(db.Text)
        win_amount = db.Column(db.Numeric(10, 2), default=0)
        analysis_result = db.Column(db.Text)
        # 新增字段
        prompt = db.Column(db.Text)  # 用户输入的提示词
        ai_response = db.Column(db.Text)  # AI的原始响应
        analysis_process = db.Column(db.Text)  # 分析过程
        exclusion_analysis = db.Column(db.Text)  # 互斥关系分析
        created_at = db.Column(db.DateTime, default=db.func.current_timestamp())
        
        def get_predicted_numbers(self):
            try:
                return json.loads(self.predicted_numbers)
            except:
                return []
        
        def set_predicted_numbers(self, numbers):
            self.predicted_numbers = json.dumps(numbers, ensure_ascii=False)
        
        def set_actual_result(self, result):
            self.actual_result = json.dumps(result, ensure_ascii=False)
        
        def to_dict(self):
            return {
                'id': self.id,
                'start_draw': self.start_draw,
                'end_draw': self.end_draw,
                'data_count': self.data_count,
                'predicted_numbers': self.get_predicted_numbers(),
                'actual_result': json.loads(self.actual_result) if self.actual_result else None,
                'win_info': self.win_info,
                'win_amount': float(self.win_amount) if self.win_amount else 0,
                'analysis_result': self.analysis_result,
                'prompt': self.prompt,
                'ai_response': self.ai_response,
                'analysis_process': self.analysis_process,
                'exclusion_analysis': self.exclusion_analysis,
                'created_at': self.created_at.isoformat()
            }
    
    class SystemConfig(db.Model):
        __tablename__ = 'system_config'
        id = db.Column(db.Integer, primary_key=True)
        key = db.Column(db.String(100), unique=True, nullable=False)
        value = db.Column(db.Text)
        description = db.Column(db.String(200))
        created_at = db.Column(db.DateTime, default=db.func.current_timestamp())
        updated_at = db.Column(db.DateTime, default=db.func.current_timestamp(), onupdate=db.func.current_timestamp())
    
    # 认证蓝图
    auth_bp = Blueprint('auth', __name__)
    
    @auth_bp.route('/login', methods=['POST'])
    def login():
        try:
            data = request.get_json()
            username = data.get('username')
            password = data.get('password')
            
            # 简单的用户验证（实际项目中应该使用数据库）
            if username == 'admin' and password == 'admin123':
                access_token = create_access_token(identity=username)
                return jsonify({'access_token': access_token}), 200
            else:
                return jsonify({'error': '用户名或密码错误'}), 401
        except Exception as e:
            return jsonify({'error': f'登录失败: {str(e)}'}), 500
    
    # 双色球蓝图
    lottery_bp = Blueprint('lottery', __name__)
    
    @lottery_bp.route('/update', methods=['POST'])
    @jwt_required()
    def update_lottery_data():
        try:
            # 使用爬虫服务更新数据
            lottery_crawler = LotteryCrawler()
            result = lottery_crawler.crawl_lottery_data(max_pages=3, target_count=30)
            print("爬取数据为："+str(result))
            
            if result.get('success'):
                # 保存到数据库
                new_count = 0
                for data in result.get('data', []):
                    # 检查是否已存在
                    existing = LotteryResult.query.filter_by(draw_number=data['draw_number']).first()
                    if not existing:
                        lottery_result = LotteryResult(
                            draw_date=data['draw_date'],
                            draw_number=data['draw_number'],
                            red_ball_1=data['red_balls'][0],
                            red_ball_2=data['red_balls'][1],
                            red_ball_3=data['red_balls'][2],
                            red_ball_4=data['red_balls'][3],
                            red_ball_5=data['red_balls'][4],
                            red_ball_6=data['red_balls'][5],
                            blue_ball=data['blue_ball'],
                            prize_info=data.get('prize_info', '')
                        )
                        db.session.add(lottery_result)
                        new_count += 1
                
                db.session.commit()
                total_count = LotteryResult.query.count()
                
                return jsonify({
                    'message': '数据更新成功',
                    'new_count': new_count,
                    'total_count': total_count,
                    'crawler_result': result
                }), 200
            else:
                return jsonify({'error': result.get('error', '爬取失败')}), 500
        except Exception as e:
            db.session.rollback()
            return jsonify({'error': f'数据更新失败: {str(e)}'}), 500
    
    @lottery_bp.route('/statistics', methods=['GET'])
    @jwt_required()
    def get_statistics():
        try:
            total_count = LotteryResult.query.count()
            latest_draw = LotteryResult.query.order_by(LotteryResult.draw_date.desc()).first()
            
            return jsonify({
                'total_count': total_count,
                'latest_draw': latest_draw.to_dict() if latest_draw else None
            }), 200
        except Exception as e:
            return jsonify({'error': f'获取统计数据失败: {str(e)}'}), 500
    
    @lottery_bp.route('/list', methods=['GET'])
    @jwt_required()
    def get_lottery_list():
        try:
            page = request.args.get('page', 1, type=int)
            per_page = request.args.get('per_page', 20, type=int)
            draw_number = request.args.get('draw_number')
            
            query = LotteryResult.query
            
            # 期数筛选
            if draw_number:
                query = query.filter(LotteryResult.draw_number == draw_number)
            
            # 排序和分页
            query = query.order_by(LotteryResult.draw_date.desc())
            pagination = query.paginate(
                page=page, 
                per_page=per_page, 
                error_out=False
            )
            
            results = [item.to_dict() for item in pagination.items]
            
            return jsonify({
                'data': results,
                'pagination': {
                    'page': page,
                    'per_page': per_page,
                'total': pagination.total,
                'pages': pagination.pages,
                    'has_next': pagination.has_next,
                    'has_prev': pagination.has_prev
                }
            }), 200
            
        except Exception as e:
            return jsonify({'error': f'获取数据失败: {str(e)}'}), 500
    
    @lottery_bp.route('/range', methods=['GET'])
    @jwt_required()
    def get_lottery_range():
        """获取彩票数据范围"""
        try:
            # 获取最早和最晚的期数
            earliest = LotteryResult.query.order_by(LotteryResult.draw_date.asc()).first()
            latest = LotteryResult.query.order_by(LotteryResult.draw_date.desc()).first()
            
            if not earliest or not latest:
                return jsonify({
                    'earliest_draw': None,
                    'latest_draw': None,
                    'total_count': 0
                }), 200
            
            return jsonify({
                'earliest_draw': earliest.draw_number,
                'latest_draw': latest.draw_number,
                'earliest_date': earliest.draw_date.isoformat(),
                'latest_date': latest.draw_date.isoformat(),
                'total_count': LotteryResult.query.count()
            }), 200
            
        except Exception as e:
            return jsonify({'error': f'获取数据范围失败: {str(e)}'}), 500
    
    # AI分析蓝图
    ai_bp = Blueprint('ai', __name__)
    
    @ai_bp.route('/analyze', methods=['POST'])
    @jwt_required()
    def analyze_data():
        try:
            data = request.get_json()
            if not data:
                return jsonify({'error': '请求数据为空'}), 400
            
            start_draw = data.get('start_draw')
            end_draw = data.get('end_draw')
            custom_prompt = data.get('prompt', '')
            
            # 验证参数
            is_valid, error_msg = DataValidator.validate_analysis_params(start_draw, end_draw, 0)
            if not is_valid:
                return jsonify({'error': error_msg}), 400
            
            # 获取历史数据
            lottery_data = LotteryResult.query.filter(
                LotteryResult.draw_number >= start_draw,
                LotteryResult.draw_number <= end_draw
            ).order_by(LotteryResult.draw_date.asc()).all()
            
            if not lottery_data:
                return jsonify({'error': '没有找到历史数据'}), 400
            
            # 检查数据量
            if len(lottery_data) > 100:
                return jsonify({'error': '分析数据量过大，请选择不超过100期的数据'}), 413
            
            # 获取互斥关系数据
            exclusion_analysis = analysis_service.analyze_red_ball_exclusion(lottery_data)
            
            # 调用AI服务进行分析
            print("开始调用AI进行分析")
            try:
                ai_result = ai_service.analyze_lottery_data(lottery_data, custom_prompt)
                print(f"AI分析完成，预测数量: {len(ai_result.get('predictions', []))}")
            except Exception as ai_error:
                print(f"AI分析失败: {ai_error}")
                # 如果AI分析失败，使用简化处理
                ai_result = {
                    'predictions': [],
                    'analysis': f'基于{len(lottery_data)}期历史数据的分析结果（AI服务暂时不可用）',
                    'prompt': custom_prompt or f"基于{len(lottery_data)}期历史数据"
                }
            # 保存预测记录
            prediction_record = AIPrediction(
                start_draw=start_draw,
                end_draw=end_draw,
                data_count=len(lottery_data),
                predicted_numbers=json.dumps(ai_result.get('predictions', [])),
                analysis_result=ai_result.get('analysis', ''),
                # 保存新增字段
                prompt=custom_prompt,
                ai_response=ai_result.get('analysis', ''),  # AI的原始响应
                analysis_process=json.dumps(ai_result.get('analysis_details', {}), ensure_ascii=False),
                exclusion_analysis=json.dumps(exclusion_analysis, ensure_ascii=False)
            )
            
            db.session.add(prediction_record)
            db.session.commit()
            
            return jsonify({
                'predictions': ai_result.get('predictions', []),
                'analysis': ai_result.get('analysis', ''),
                'prediction_id': prediction_record.id,
                'data_count': len(lottery_data)
            }), 200
            
        except Exception as e:
            db.session.rollback()
            app.logger.error(f"AI分析失败: {e}")
            return jsonify({'error': f'分析失败: {str(e)}'}), 500
    
    @ai_bp.route('/mutual-exclusion', methods=['POST'])
    @jwt_required()
    def analyze_mutual_exclusion():
        try:
            data = request.get_json()
            if not data:
                return jsonify({'error': '请求数据为空'}), 400
            
            period_count = data.get('period_count', 50)
            start_draw = data.get('start_draw')
            
            # 获取数据
            if start_draw:
                recent_data = LotteryResult.query.filter(
                    LotteryResult.draw_number >= start_draw
                ).order_by(LotteryResult.draw_date.desc()).limit(period_count).all()
            else:
                recent_data = LotteryResult.query.order_by(
                    LotteryResult.draw_date.desc()
                ).limit(period_count).all()
                
            if len(recent_data) < 10:
                return jsonify({'error': '数据量不足，无法进行有效分析'}), 400
            
            # 使用分析服务
            result = analysis_service.analyze_red_ball_exclusion(recent_data)
            
            return jsonify({
                'period_count': len(recent_data),
                'analysis': result
            }), 200
            
        except Exception as e:
            app.logger.error(f"互斥分析失败: {e}")
            return jsonify({'error': f'分析失败: {str(e)}'}), 500
    
    @ai_bp.route('/predictions', methods=['GET'])
    @jwt_required()
    def get_predictions():
        """获取AI预测历史"""
        try:
            page = request.args.get('page', 1, type=int)
            per_page = request.args.get('per_page', 10, type=int)
            
            # 查询预测记录
            query = AIPrediction.query.order_by(AIPrediction.created_at.desc())
            pagination = query.paginate(
                page=page, 
                per_page=per_page, 
                error_out=False
            )
            
            results = [item.to_dict() for item in pagination.items]
            
            return jsonify({
                'data': results,
                'total': pagination.total,
                'page': page,
                'per_page': per_page,
                'pages': pagination.pages,
                'has_next': pagination.has_next,
                'has_prev': pagination.has_prev
            }), 200
            
        except Exception as e:
            app.logger.error(f"获取预测历史失败: {e}")
            return jsonify({'error': f'获取预测历史失败: {str(e)}'}), 500
    
    @ai_bp.route('/predictions/<int:prediction_id>', methods=['GET'])
    @jwt_required()
    def get_prediction_detail(prediction_id):
        """获取预测详情"""
        try:
            prediction = AIPrediction.query.get_or_404(prediction_id)
            return jsonify(prediction.to_dict()), 200
        except Exception as e:
            app.logger.error(f"获取预测详情失败: {e}")
            return jsonify({'error': f'获取预测详情失败: {str(e)}'}), 500
    
    @ai_bp.route('/verify', methods=['POST'])
    @jwt_required()
    def verify_prediction():
        """验证预测结果"""
        try:
            data = request.get_json()
            if not data:
                return jsonify({'error': '请求数据为空'}), 400
            
            prediction_id = data.get('prediction_id')
            actual_draw_number = data.get('draw_number')
            actual_red_balls = data.get('red_balls', [])
            actual_blue_ball = data.get('blue_ball')
            
            if not prediction_id or not actual_draw_number:
                return jsonify({'error': '缺少必要参数'}), 400
            
            # 获取预测记录
            prediction = AIPrediction.query.get(prediction_id)
            if not prediction:
                return jsonify({'error': '预测记录不存在'}), 404
            
            # 验证实际开奖号码
            if not DataValidator.validate_ball_numbers(actual_red_balls, actual_blue_ball):
                return jsonify({'error': '开奖号码格式无效'}), 400
            
            # 保存实际结果
            actual_result = {
                'draw_number': actual_draw_number,
                'red_balls': actual_red_balls,
                'blue_ball': actual_blue_ball
            }
            prediction.set_actual_result(actual_result)
            
            # 计算中奖情况
            predicted_numbers = prediction.get_predicted_numbers()
            
            # 使用AI服务验证预测结果
            try:
                # 创建临时的实际结果对象
                class TempResult:
                    def __init__(self, red_balls, blue_ball):
                        self.red_balls = red_balls
                        self.blue_ball = blue_ball
                    def get_red_balls(self):
                        return self.red_balls
                
                temp_actual = TempResult(actual_red_balls, actual_blue_ball)
                verify_result = ai_service.verify_prediction(predicted_numbers, temp_actual)
                
                win_info = {
                    'win_info': verify_result['win_info'],
                    'win_amount': verify_result['win_amount'],
                    'total_groups': verify_result['total_groups']
                }
            except Exception as verify_error:
                print(f"AI验证失败，使用本地计算: {verify_error}")
                # 如果AI验证失败，使用本地计算
                win_info = calculate_win_level_for_all_groups(predicted_numbers, actual_red_balls, actual_blue_ball)
            
            prediction.win_info = json.dumps(win_info, ensure_ascii=False)
            prediction.win_amount = win_info.get('win_amount', 0)
            
            db.session.commit()
            
            return jsonify({
                'prediction_id': prediction_id,
                'win_info': win_info,
                'message': '验证完成'
            }), 200
            
        except Exception as e:
            db.session.rollback()
            app.logger.error(f"验证预测失败: {e}")
            return jsonify({'error': f'验证失败: {str(e)}'}), 500
    
    # 报告蓝图
    reports_bp = Blueprint('reports', __name__)
    
    @reports_bp.route('/summary', methods=['GET'])
    @jwt_required()
    def get_summary():
        """获取系统摘要报告"""
        try:
            total_lottery = LotteryResult.query.count()
            total_predictions = AIPrediction.query.count()
            latest_draw = LotteryResult.query.order_by(LotteryResult.draw_date.desc()).first()
            
            return jsonify({
                'total_lottery': total_lottery,
                'total_predictions': total_predictions,
                'latest_draw': latest_draw.to_dict() if latest_draw else None,
                'last_updated': datetime.now().isoformat()
            }), 200
        except Exception as e:
            app.logger.error(f"获取摘要报告失败: {e}")
            return jsonify({'error': f'获取摘要报告失败: {str(e)}'}), 500

    @reports_bp.route('/winning-analysis', methods=['GET'])
    @jwt_required()
    def get_winning_analysis():
        """获取中奖分析报告"""
        try:
            # 获取最近的预测记录
            recent_predictions = AIPrediction.query.order_by(
                AIPrediction.created_at.desc()
            ).limit(10).all()
            
            analysis_data = []
            for pred in recent_predictions:
                if pred.actual_result:
                    try:
                        actual = json.loads(pred.actual_result)
                        predicted = pred.get_predicted_numbers()
                        
                        # 计算中奖情况
                        win_info = {
                            'prediction_id': pred.id,
                            'start_draw': pred.start_draw,
                            'end_draw': pred.end_draw,
                            'predicted_numbers': predicted,
                            'actual_result': actual,
                            'win_amount': float(pred.win_amount) if pred.win_amount else 0
                        }
                        analysis_data.append(win_info)
                    except:
                        continue
            
            return jsonify({
                'winning_analysis': analysis_data,
                'total_analyzed': len(analysis_data)
            }), 200
        except Exception as e:
            app.logger.error(f"获取中奖分析失败: {e}")
            return jsonify({'error': f'获取中奖分析失败: {str(e)}'}), 500

    @reports_bp.route('/prediction-trends', methods=['GET'])
    @jwt_required()
    def get_prediction_trends():
        """获取预测趋势报告"""
        try:
            # 获取最近30天的预测记录
            thirty_days_ago = datetime.now() - timedelta(days=30)
            recent_predictions = AIPrediction.query.filter(
                AIPrediction.created_at >= thirty_days_ago
            ).order_by(AIPrediction.created_at.asc()).all()
            
            trends_data = []
            for pred in recent_predictions:
                trends_data.append({
                    'date': pred.created_at.strftime('%Y-%m-%d'),
                    'prediction_count': 1,
                    'data_count': pred.data_count
                })
            
            return jsonify({
                'prediction_trends': trends_data,
                'total_predictions': len(trends_data)
            }), 200
        except Exception as e:
            app.logger.error(f"获取预测趋势失败: {e}")
            return jsonify({'error': f'获取预测趋势失败: {str(e)}'}), 500
    
    # 注册蓝图
    app.register_blueprint(auth_bp, url_prefix='/api/auth')
    app.register_blueprint(lottery_bp, url_prefix='/api/lottery')
    app.register_blueprint(ai_bp, url_prefix='/api/ai')
    app.register_blueprint(reports_bp, url_prefix='/api/reports')
    
def calculate_win_level_for_all_groups(predicted_numbers, actual_red_balls, actual_blue_ball):
    """计算所有预测组的中奖等级和金额，并返回明细用于前端标记中奖号码"""
    if not predicted_numbers or not actual_red_balls:
        return {
            'win_info': '无中奖',
            'win_amount': 0,
            'total_groups': 0,
            'verification_results': []
        }

    win_info_list = []
    total_amount = 0
    details = []

    # 处理多组预测
    if isinstance(predicted_numbers, list):
        groups = predicted_numbers
    else:
        groups = [predicted_numbers]

    for i, group in enumerate(groups):
        if not group:
            continue

        predicted_reds = group.get('red_balls', []) or []
        predicted_blue = group.get('blue_ball')

        # 计算红球匹配数及命中列表
        matched_reds = [b for b in predicted_reds if b in actual_red_balls]
        red_matches = len(matched_reds)

        # 计算蓝球匹配
        blue_match = predicted_blue == actual_blue_ball

        # 判断中奖等级与金额
        if red_matches == 6 and blue_match:
            level = 1; amount = 5000000
        elif red_matches == 6 and not blue_match:
            level = 2; amount = 100000
        elif red_matches == 5 and blue_match:
            level = 3; amount = 3000
        elif red_matches == 5 and not blue_match:
            level = 4; amount = 200
        elif red_matches == 4 and blue_match:
            level = 4; amount = 200
        elif red_matches == 4 and not blue_match:
            level = 5; amount = 10
        elif red_matches == 3 and blue_match:
            level = 5; amount = 10
        elif blue_match and red_matches in (0, 1, 2):
            level = 6; amount = 5
        else:
            level = 0; amount = 0

        level_names = {1: '一等奖', 2: '二等奖', 3: '三等奖', 4: '四等奖', 5: '五等奖', 6: '六等奖'}

        if level > 0:
            win_info_list.append(f"第{i+1}组: {level_names[level]} {amount}元")
            total_amount += amount
        else:
            win_info_list.append(f"第{i+1}组: 未中奖")

        details.append({
            'group_index': i + 1,
            'predicted_red_balls': predicted_reds,
            'predicted_blue_ball': predicted_blue,
            'matched_red_balls': matched_reds,
            'matched_blue_ball': bool(blue_match),
            'red_matches': red_matches,
            'blue_match': bool(blue_match),
            'level': level,
            'level_name': level_names.get(level, '未中奖'),
            'amount': amount
        })

    return {
        'win_info': '; '.join(win_info_list),
        'win_amount': total_amount,
        'total_groups': len(groups),
        'verification_results': details
    }

def calculate_win_level(predicted_numbers, actual_red_balls, actual_blue_ball):
    """计算中奖等级和金额"""
    if not predicted_numbers or not actual_red_balls:
        return {'level': 0, 'amount': 0, 'message': '无中奖'}
    
    # 计算红球匹配数
    red_matches = 0
    for pred_red in predicted_numbers.get('red_balls', []):
        if pred_red in actual_red_balls:
            red_matches += 1
    
    # 计算蓝球匹配
    blue_match = predicted_numbers.get('blue_ball') == actual_blue_ball
    
    # 判断中奖等级
    if red_matches == 6 and blue_match:
        level = 1
        amount = 5000000  # 一等奖
    elif red_matches == 6 and not blue_match:
        level = 2
        amount = 100000   # 二等奖
    elif red_matches == 5 and blue_match:
        level = 3
        amount = 3000     # 三等奖
    elif red_matches == 5 and not blue_match:
        level = 4
        amount = 200      # 四等奖
    elif red_matches == 4 and blue_match:
        level = 4
        amount = 200      # 四等奖
    elif red_matches == 4 and not blue_match:
        level = 5
        amount = 10       # 五等奖
    elif red_matches == 3 and blue_match:
        level = 5
        amount = 10       # 五等奖
    elif red_matches == 2 and blue_match:
        level = 6
        amount = 5        # 六等奖
    elif red_matches == 1 and blue_match:
        level = 6
        amount = 5        # 六等奖
    elif red_matches == 0 and blue_match:
        level = 6
        amount = 5        # 六等奖
    else:
        level = 0
        amount = 0
    
    level_names = {
        1: '一等奖', 2: '二等奖', 3: '三等奖',
        4: '四等奖', 5: '五等奖', 6: '六等奖'
    }
    
    return {
        'level': level,
        'level_name': level_names.get(level, '未中奖'),
        'amount': amount,
        'red_matches': red_matches,
        'blue_match': blue_match,
        'message': f'{level_names.get(level, "未中奖")} ¥{amount}' if level > 0 else '未中奖'
    }

def main():
    app, db = create_app()
    
    with app.app_context():
        db.create_all()
    
    # 关闭自动重载器以避免 Windows 上带空格路径导致的重启失败
    app.run(debug=True, use_reloader=False, host='0.0.0.0', port=5000)

if __name__ == '__main__':
    main() 
